import axios from "axios";
import { Toast, Dialog } from "vant";
import sessionStorage from "@/utils/sessionStorage";
import router from "@/router";
import qs from "qs";
import cookie from '@/utils/cookie.js';
// 创建axios实例
const service = axios.create({
  // baseURL: www.cbda1984.com // , // api 的 base_url
  // baseURL: 'http://111.229.30.99:8181'
  baseURL: 'http://api.cbda1984.com'
  // timeout: 5000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  config => {
    // let userInfo = sessionStorage.get("userInfo");
    let userInfo = cookie.readCookie('userInfo') ? JSON.parse(cookie.readCookie('userInfo')) : {};
    if (userInfo && userInfo.userCode) {
      config.headers["Authorization"] = userInfo.userCode || ''; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    const data = config.data;
    if (data && data.code) {
      sessionStorage.set("wxcode", data.code);

    }
    if (data && data.get instanceof Function) {
      // 如果是上传文件或图片  不格式化参数

      if (data.get("file")) {
      } else {
        config.data = qs.stringify(data, { allowDots: true });
      }
    } else {
      config.data = qs.stringify(data, { allowDots: true });
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */

    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 10400) {
        Dialog.confirm({
          title: "",
          message: "您需要登陆才能继续访问内容,您是否要登陆?"
        })
          .then(() => {
            router.push({
              path: "/login"
            });
          })
          .catch(() => {
            router.back(-1);
          });
      } else if (res.code === 12005) {
        return response.data;
      }

      return response.data;
    } else {
      return response.data;
    }
  },
  error => {
    console.log("err" + error); // for debug
    //Toast.fail(error.message);
    return Promise.reject(error);
  }
);

export default service;
